<template>
  <div>
    <el-table-form ref="dataForm" class="form" :model="shop" label-position="right" label-width="80px">
      <el-form-item label="商品分类:" prop="orgSNNo">
        <el-tree-select
          v-model="shop.gtId"
          :clearable="false"
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择商品分类',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'gtId',
              label: 'gtName',
              disabled: 'disabled',
            },
            data: goodsTreeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="商品名称:" class="merge-item">
        <el-select v-model="shop.goodsId" clearable>
          <el-option v-for="(l,i) in goodsTypesDetailList" :key="i" :value="l.goodsId" :label="l.goodsName" />
        </el-select>
      </el-form-item>
      <el-form-item label="生效机构:" prop="orgSNNo">
        <el-tree-select
          v-model="shop.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择组织机构',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: orgTreeData
          }"
          @node-click="selectOrgTreeChange"
        />
      </el-form-item>
      <el-form-item label="波动方式:" class="merge-item">
        <el-select v-model="shop.priceType" clearable>
          <el-option v-for="(l,i) in priceTypeMap" :key="i" :value="l.value" :label="l.desc" />
        </el-select>
      </el-form-item>
      <el-form-item label="价格:" class="merge-item">
        <el-input v-model="shop.price" clearable placeholder="请输入" @keyup.enter.native="search" />
      </el-form-item>
      <el-form-item label="" label-width="0" class="merge-item">
        <el-checkbox v-model="disAbledStatu">排除已失效</el-checkbox>
      </el-form-item>
      <template v-slot:btns>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button type="primary" style="margin-right: 5px;" icon="el-icon-add" @click="add">新增调价</el-button>
        <el-button type="primary" icon="el-icon-download" :loading="$loadingPlugin.exportFile" @click="exportFile">导出</el-button>
      </div>
    </div>
    <div class="page_main">
      <div class="left">
        <div class="info-title">
          <span class="title-icon" />
          <span>商品信息</span>
        </div>
        <lb-table
          ref="lbTable_left"
          v-loading="$loadingPlugin.fetchData"
          v-el-height-adaptive-table="{bottomOffset:10}"
          border
          element-loading-text="加载中"
          :column="tableDataLeft.column"
          :data="tableDataLeft.data"
          highlight-current-row
          :total="tableDataLeft.total"
          custom-column
          height="300"
          @current-change="selectLeftTable"
          @fetch="fetchDataLeft"
        />
      </div>
      <div class="right">
        <div class="info-title">
          <span class="title-icon" />
          <span>客户信息</span>
        </div>
        <lb-table
          ref="tableData_right"
          v-loading="$loadingPlugin.fetchData"
          v-el-height-adaptive-table="{bottomOffset:10}"
          border
          element-loading-text="加载中"
          :column="tableDataRight.column"
          :data="tableDataRight.data"
          pagination
          highlight-current-row
          :total="tableDataRight.total"
          @fetch="fetchDataRight"
        />
      </div>

    </div>
    <addSelectPrice ref="addSelectPrice" :goods-tree-data="goodsTreeData" :org-tree-data="orgTreeData" />
    <allAdjust ref="allAdjust" :goods-tree-data="goodsTreeData" :org-tree-data="orgTreeData" @afterSave="afterSave" />
  </div>
</template>

<script>
  import { goodsTypeDetail, CmsSpecialPriceOriented, CmsSpecialPriInfo, specialPriceGoodsExport } from '@/api'
  import { parseTime } from '@/utils'
  export default {
    name: 'shopOrientedMode',
    components: {
      addSelectPrice: require('./addSelectPrice.vue').default,
      allAdjust: require('./allAdjust.vue').default
    },
    props: ['orgTreeData', 'goodsTreeData', 'exportDomain'],

    data() {
      return {
        startNum: 0, // 用作首次加载表格不执行
        goodsTypesDetailList: [],
        disAbledStatu: true,
        priceTypeMap: [{ 'value': 1, 'desc': '下浮', 'key': 'Fluctuating' }, { 'value': 2, 'desc': '固定', 'key': 'Fixed' }],
        shop: {
          gtId: null,
          goodsId: null
        },
        tableDataLeft: {
          data: [],
          column: [
            { label: '商品名称', prop: 'goodsName', width: 200, align: 'center' },
            { label: '波动方式', prop: 'priceType', width: '', align: 'center',
              render: (h, { row }) => <span>{row.priceType && this.priceTypeMap.find(l => l.value === row.priceType).desc }</span>
            },
            { label: '波动价格', prop: 'price', width: '', align: 'right',
              render: (h, { row, column }) => <span>{row.price && row.price.toFixed(2) }</span>
            },
            { label: '操作', prop: 'op', width: '', align: 'center',
              render: (h, { row, column }) => <span onClick={() => { this.allAdjust(row) }} style='color:blue;cursor: pointer'>批量调价</span>
            }
          ]
        },
        tableDataRight: {
          total: 0,
          column: [
            { label: '客户名称', prop: 'csmName', width: 120, align: 'center' },
            { label: '状态', prop: 'checkStatus', width: 80, align: 'center',
              render: (h, { row, column }) => <span>{this.statusMap(row, column) }</span>
            },
            { label: '时效范围', prop: 'startDt', width: 300, align: 'center',
              render: (h, { row, column }) => <span>{this.timeformat(row, column) }</span>
            },
            { label: '客户编号', prop: 'csmCode', width: 80, align: 'center' },
            { label: '客户电话', prop: 'contactPhone', width: 120, align: 'center' },
            { label: '客户地址', prop: 'csmAddress', width: 250, align: 'center' },
            { label: '生效机构', prop: 'scopeOrgName', width: 180, align: 'center' },
            { label: '关键字', prop: 'keyName', width: 80, align: 'center' }
          ],
          data: []
        },
        rightParams: {}

      }
    },
    methods: {
      async search() {
        // console.log(this.shop)
        // try {
        //   var params = { ...this.shop }
        //   var res = await CmsSpecialPriceOriented(params)
        //   console.log(res)
        // } catch (e) {
        //   console.log(e)
        // }
        this.fetchDataLeft()
      },
      async fetchDataLeft() {
        // 首次不加载
        if (!this.startNum) {
          this.startNum++
          return
        }
        // ////////
        if (JSON.stringify(this.shop) === '{}') {
          return
        }
        if (!this.shop.goodsId) {
          this.$message.warning('请选择商品')
          return
        }
        const params = {
          ...this.shop,
          pageIndex: 1,
          pageSize: 999
        }
        const res = await CmsSpecialPriceOriented(params)
        this.tableDataLeft.data = res.data
        // if (currentPage === 1) this.tableData.total = res.data.total
      },
      async afterSave() {
        await this.fetchDataLeft()
      },
      async fetchDataRight({ pageIndex = 1, pageSize = 20 }, data) {
        if (JSON.stringify(this.shop) === '{}') {
          return
        }
        const params = {
          ...this.rightParams,
          pageIndex,
          pageSize
        }
        if (!params.price) return
        const res = await CmsSpecialPriInfo(params)
        this.tableDataRight.data = res.data.rows
        if (pageIndex === 1) this.tableDataRight.total = res.data.total
      },
      selectLeftTable(val) {
        // console.log(val, 'val')
        const params = { 'goodsId': val.goodsId, 'priceType': val.priceType, 'price': val.price, 'scopeOrgSNNo': val.orgSNNo }
        this.rightParams = params
        if (this.disAbledStatu) params['expired'] = 2
        this.fetchDataRight({}, params)
      },

      // 选择商品分类
      async selectTreeChange(value) {
        // this.orgSNNo = value.orgSNNo
        this.shop.goodsId = ''
        if (value) {
          await this.getGoodsTypeDetails(value.gtId)
        }
      },
      // 选择生效机构
      selectOrgTreeChange(value) {
        // this.orgSNNo = value.orgSNNo
      },
      // 获取商品分类详情
      async getGoodsTypeDetails(val) {
        try {
          const res = await goodsTypeDetail({ gtId: val })
          this.goodsTypesDetailList = res.data.rows
          // console.log(res)
        } catch (error) {
          console.log(error)
        }
      },
      // 批量调价
      allAdjust(row) {
        this.$refs.allAdjust.open(row)
      },
      // 状态文本格式化
      statusMap(row, column) {
        if (row.endDt < row.nowDt) {
          return '已失效'
        }
        const val = row[column.property]
        if (val === 0) {
          return '一级待审'
        } else if (val === 1) {
          return '二级待审'
        } else if (val === 2) {
          return '已生效'
        } else if (val === 4) {
          return '已驳回'
        }
        return ''
      },
      // 新增调价
      add() {
        this.$refs.addSelectPrice.open()
      },
      // 时间格式化
      timeformat(row, column) {
        const startTime = parseTime(row.startDt, '{y}-{m}-{d} {h}:{i}:{s}')
        const endTime = parseTime(row.endDt, '{y}-{m}-{d} {h}:{i}:{s}')
        return `${startTime}至${endTime}`
      },
      // 导出
      async exportFile() {
        // console.log(this.exportDomain)
        // console.log(url)
        this.$confirm('确定要导出吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          var list = JSON.parse(JSON.stringify(this.tableDataRight.column))
          // list.pop()
          const value = {}
          list.forEach(l => {
            value[l.prop] = l.label
            return value
          })
          if (!this.shop.goodsId) {
            this.$message.warning('请选择商品')
            return
          }
          const params = {
            kv: value,
            paramData: { ...this.shop }
          }
          await specialPriceGoodsExport(params).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        }).catch(() => {

        })
      }

    }
  }
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
}
.form_right {
  display: flex;
  flex-wrap: wrap;
  & /deep/ .el-form-item {
    width: 40%;
    padding-right: 10px;
    .el-form-item__content > .el-select {
      width: 100%;
    }
  }
}
.info-title {
  display: flex;
  align-items: center;
  margin-top: 8px;
  margin-bottom: 10px;
  font-size: 14px;
  .title-icon {
    display: inline-block;
    width: 4px;
    height: 14px;
    margin-right: 6px;
    background: $themeColor;
  }
  span {
    font-weight: 700;
    color: $themeColor;
  }
}
.page_main {
  display: flex;
  box-sizing: border-box;
  .left {
    width: 30%;
    padding: 5px;
    // border: 1px solid #ebeff6;
  }
  .right {
    width: 70%;
    padding: 5px;
  }
  .info {
    display: inline-block;
    overflow: hidden;
    font-size: 12px;
    color: #999;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: bottom;
  }
}
</style>
